#include "main.h"
#include "login.h"
#include "ui_login.h"
#include "signup.h"
#include "firstwindow.h"
#include <QGraphicsDropShadowEffect>
#include <localdb.h>

login::login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);

    this->setWindowTitle("IM_software login");
    this->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));

    QPixmap *pix = new QPixmap(":/new/prefix1/images/blue.png");
    QSize sz = ui->label_image->size();
    ui->label_image->setPixmap(pix->scaled(sz));

    //设置阴影
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setOffset(-3, 0);
    shadow->setColor(QColor("#888888"));
    shadow->setBlurRadius(30);
    ui->label_image->setGraphicsEffect(shadow);

    QString hostName = QHostInfo::localHostName();
    QHostInfo hostInfo = QHostInfo::fromName(hostName);
    QList<QHostAddress> addrlist = hostInfo.addresses();
    for(int i=0;i<addrlist.count();i++)
    {
        QHostAddress host = addrlist.at(i);
        if(QAbstractSocket::IPv4Protocol == host.protocol())
        {
            //QString ip = host.toString();
            user_ip = host.toString();
            //            ui->uiip->addItem(ip);
        }
    }

    m_socket = new SerSocket(this);


    //connect(m_socket,&SerSocket::stateChanged,this,&Widget::on_statechange);
    //connect(this,&Widget::ConnectToServer,m_socket,&SerSocket::ClientConnectToHost);
    connect(this,&login::Online,m_socket,&SerSocket::ClientSendingText);
    connect(m_socket,&SerSocket::ServerSendList,this,&login::getList);
    connect(m_socket,&SerSocket::SignalSign,this,&login::on_login_success);
    connect(m_socket,&SerSocket::SignalSignError,this,&login::on_login_error);

    //    connect(this,&Widget::heart_jump,m_socket,&SerSocket::Jump);

    //    connect(m_socket,&SerSocket::SignalUID,this,[&](const QString& uid){
    //        use_uid = uid;
    //        sign_info->insert("UID",uid);
    //    });
    //    connect(m_socket,&SerSocket::Updatefinish,this,[&](){ update_finish = true;});
    //    connect(m_socket,&SerSocket::FileSucccess,this,[&](){ notsend = false;});

    //    connect(m_socket,&SerSocket::connected,this,&Widget::on_connected);
    //    connect(m_socket,&SerSocket::disconnected,this,&Widget::on_disconnected);






    //初始化数据库
    //    sqlite_Init();
}

login::~login()
{
    delete ui;
}

void sqlite_Init()
{

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("user.db");
    if(!db.open())
    {
        qDebug()<<"open error";
    }
    //create excle
    QString createsql=QString("create table if not exists user(id integer primary key autoincrement,"
                              "username ntext unique not NULL,"
                              "password ntext not NULL)");
    QSqlQuery query;
    if(!query.exec(createsql)){
        qDebug()<<"table create error";
    }
    else{
        qDebug()<<"table create success";
    }
}

void login::on_btn_signin_clicked()
{
    sqlite_Init();
    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();

    //use_ip = ui->uiip->currentText();
    //Friend LocalDB::GetFriend(int id){

    use_uid = username;
    use_ip = user_ip;

    sign_info = new QJsonObject;
    sign_info->insert("UID",username);
    sign_info->insert("password",password);
    sign_info->insert("ip",user_ip);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(*sign_info);
    //m_socket->on_send(data_encoder(sbag,cmd));
    emit Online(jsonDocument.toJson(),0x05);
    //onsign = true;


    //    QString sql=QString("select * from user where username='%1' and password='%2'")
    //            .arg(username).arg(password);
    //    //创建执行语句对象
    //    QSqlQuery query(sql);
    //    //判断执行结果
    //    if(!query.next())
    //    {
    //        qDebug()<<"Login error";
    //        QMessageBox::information(this,"登录认证","登录失败,账户或者密码错误");

    //    }
    //    else
    //    {
    //        qDebug()<<"Login success";
    //        QMessageBox::information(this,"登录认证","登录成功");
    //                                 firstwindow *F = new firstwindow;
    //        F->show();;

    //        this->close();
    //    }
}

void login::on_btn_signup_clicked()
{
    this->close();
    signup *s = new signup;
    s->show();
}

void login::on_login_success(){
    qDebug()<<"Login success";
    QMessageBox::information(this,"登录认证","登录成功");
    firstwindow *F = new firstwindow;
    F->show();

    this->close();
}
void login::on_login_error(const QString& error){
    qDebug()<<"Login error";
    QMessageBox::information(this,"登录认证","登录失败");
}

void login::getList(const QJsonArray& list,const QJsonArray& glist,const int edition)
{
    db.Connect(use_uid);
    int frdnum = list.size();
    id_list = new QJsonObject();
    name_list = new QJsonObject();
    //ui->cbox_fd->clear();
    db.DelALLFriend();
    db.DelALLGroup();
    user_list_edition = edition;
    for (int i =0; i < frdnum; i++)
    {
        QJsonObject member = list.at(i).toObject();
        if(member.value("uid").toString() ==use_uid){
            use_name = member.value("name").toString();
        }
        QString name = member.value("name").toString()+"*"+member.value("uid").toString();
        //ui->cbox_fd->addItem(name);
        QJsonObject data;
        data.insert("ip",member.value("ip").toString());
        data.insert("name",member.value("name").toString());
        db.AddFriend(member.value("uid").toString().toInt(),member.value("name").toString(),member.value("ip").toString(),member.value("job").toString());
        id_list->insert(member.value("uid").toString(),data);
        data.insert("uid",member.value("uid").toString());
        name_list->insert(name,data);}
    int gnum = glist.size();
    group_list = new QJsonObject();
    //ui->cbox_group->clear();
    for (int i =0; i < gnum; i++)
    {
        QJsonObject member = glist.at(i).toObject();
        //ui->cbox_frd->addItem(name);
        QJsonObject data;
        data.insert("category",member.value("category").toString());
        data.insert("name",member.value("name").toString());
        db.AddGroup(member.value("uid").toString().toInt(),
                    member.value("name").toString(),
                    member.value("memberList").toString(),
                    member.value("category").toString());
        group_list->insert(member.value("uid").toString(),data);
    }
    load_friend_over=true;
}
